package com.tjd.uploaddemo.controller;

import com.tjd.uploaddemo.utils.Dto;
import com.tjd.uploaddemo.utils.fileutils.FileChunk;
import com.tjd.uploaddemo.utils.fileutils.FileChunkInfo;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 分片上传Demo
 *
 * @Auther: 田金东
 * @Date: 12/12/0012
 **/
@RestController
public class FileChunkUploadController {

    private static ConcurrentHashMap<String, HashMap<String, FileChunkInfo>> map = new ConcurrentHashMap<>();

    //    @Value("${base.path}")
    private String base_path = "C:\\Users\\Lenovo\\Desktop\\tmp";


    /**
     * @param file
     * @param orginName   总文件的名称
     * @param totalChunks 文件分片个数
     * @param curentChunk 当前上传的分片号
     * @param timestamp   上传的时间戳
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    @ResponseBody
    public Dto<Object> upload(MultipartFile file, String orginName, Integer totalChunks, Integer curentChunk, String timestamp, HttpServletRequest request) throws IOException {
        Dto<Object> dto = new Dto<>();
        String sessionId = request.getSession().getId();
        //通过sessionId先获取当前会话的缓存
        HashMap<String, FileChunkInfo> sessionCached = map.get(sessionId);

        System.out.println(timestamp);
        System.out.println(sessionId);

        if (sessionCached == null) {
            synchronized (map) {
                if (map.get(sessionId) == null) {
                    sessionCached = new HashMap<>();
                    map.put(sessionId, sessionCached);
                }
            }
        }
        if (totalChunks <= 1) {
            //如果不是分片上传
            file.transferTo(new File(base_path + File.separator + sessionId + orginName));
            dto.setMsg("文件上传成功");
        } else {
            FileChunkInfo fileChunkInfo = sessionCached.get(timestamp);
            //双重校验
            if (fileChunkInfo == null) {
                synchronized (sessionCached) {
                    if (sessionCached.get(timestamp) == null) {
                        fileChunkInfo = new FileChunkInfo(orginName, base_path + File.separator + sessionId, totalChunks);
                        sessionCached.put(timestamp, fileChunkInfo);
                        File baseDir = new File(fileChunkInfo.getBasePath());
                        baseDir.mkdir();
                    }
                }
            }

            System.out.println(fileChunkInfo);

            //创建分片文件信息
            FileChunk fileChunk = new FileChunk(fileChunkInfo.getBasePath() + File.separator + curentChunk, curentChunk, timestamp, sessionId);
            //将分片文件上传至临时文件夹
            file.transferTo(new File(fileChunk.getBasePath()));
            //将分片信息放入文件信息
            fileChunkInfo.addFileChunk(fileChunk);
            if (fileChunkInfo.isFinished()) {
                //合并临时文件
                fileChunkInfo.mergeFile();
                dto.setMsg("文件上传成功");
            }
//            System.out.println(curentChunk + "号分片:" + fileChunkInfo.getChunkNum());
            dto.setMsg(curentChunk + " 分片上传成功");
        }
        return dto;
    }


}
